<template>
  <div>
    <x-search>
      <template #search>
        <p>
          用户名
          <a-input
            v-model:value="name"
            placeholder="请输入用户名"
            style="width: 150px"
          />
        </p>
        <p style="margin-left: 20px">
          角色
          <a-select
            v-model:value="role"
            placeholder="请选择角色"
            style="width: 150px"
          >
            <a-select-option
              v-for="role in allrole_arr"
              :key="role.id"
              :value="role.id"
            >
              {{ role.name }}
            </a-select-option>
          </a-select>
        </p>
        <a-button type="primary" style="margin-left: 10px" @click="but_search">
          搜索
        </a-button>
        <a-button style="margin-left: 10px" @click="reset_search">
          重置
        </a-button>
      </template>
      <template #operate>
        <a-button
          type="primary"
          style="margin-left: 10px"
          @click="showModal"
          v-checkpermission="'user_add'"
        >
          <plus-outlined style="margin-right: 0" />
          新增用户
        </a-button>
      </template>
    </x-search>

    <!-- 新增用户弹窗 -->
    <a-modal v-model:open="open" title="新增用户" @ok="handleOk">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" placeholder="请输入用户邮箱" />
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select v-model:value="formState.role" placeholder="请选择角色">
            <a-select-option
              v-for="role in allrole_arr"
              :key="role.id"
              :value="role.id"
            >
              {{ role.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="默认密码" name="password">
          <a-input v-model:value="formState.password" placeholder="请输入用户密码" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 用户表格 -->
    <a-table
      :dataSource="dataSource"
      :columns="columns"
      :pagination="{
        pageSize: pagination.pageSize,
        total: pagination.total,
        current: pagination.current,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '20', '50'],
        showTotal: (total:number) => `共 ${total} 条`,
      }"
      @change="handleTableChange"
      :scroll="{ y: 600 }"
      v-checkpermission="'user_list'"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'role_name'">
          <span>
            <button class="role-tag">
              {{ record.role_name }}
            </button>
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a-button
              type="link"
              style="width: 50px; color: #1890ff"
              @click="showModal_edit(record)"
              v-checkpermission="'user_edit'"
            >
              <EditOutlined style="margin-right: 0px" />
              编辑
            </a-button>
            <a-button
              type="link"
              danger
              style="width: 80px; color: #cf1322"
              @click="del_user_t(record.id)"
              v-checkpermission="'user_delete'"
            >
              <DeleteOutlined style="margin-right: 0px" />
              删除
            </a-button>
          </span>
        </template>
      </template>
    </a-table>

    <!-- 编辑用户弹窗 -->
    <a-modal v-model:open="open_edit" title="修改用户" @ok="handleOk_edit">
      <a-form
        ref="formRef_edit"
        :model="formState_edit"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState_edit.username" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState_edit.email" />
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select v-model:value="formState_edit.role" placeholder="请选择角色">
            <a-select-option
              v-for="role in allrole_arr"
              :key="role.id"
              :value="role.id"
            >
              {{ role.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import { EditOutlined, DeleteOutlined, PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import XSearch from "../components/XSearch.vue";
import http from "../http/http";
import { useStore } from "vuex";

const store = useStore();
const userPermiss_vuex = store.state.userPermiss;

// 权限指令
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      el.parentNode?.removeChild(el);
    }
  },
};

// 搜索相关
const name = ref("");
const role = ref<number | null>(null);
const allrole_arr = ref([
  { name: "店长", id: 1 },
  { name: "客服", id: 2 },
  { name: "财务", id: 3 },
]);


const reset_search = () => {
  name.value = "";
  role.value = null;
};

// 全部角色的接口
const all_permission = async () => {
  try {
    const results = await http.get("/api/roles/all");
    console.log(results);
    allrole_arr.value = results.data.results
  } catch (error) {
    console.error("权限获取失败:", error);
    message.error("权限获取失败");
  }
};

const but_search = () => {
  pagination.current = 1;
  user_list();
};

// 表格相关
const columns = [
  { title: "用户名", dataIndex: "username", key: "username", width: 100 },
  { title: "邮箱", dataIndex: "email", key: "email", width: 180 },
  { title: "角色", dataIndex: "role_name", key: "role_name", width: 100 },
  { title: "操作", key: "action", width: 300 },
];

const dataSource = ref([]);
const pagination = reactive({
  pageSize: 5,
  total: 0,
  current: 1,
});

const handleTableChange = (pag) => {
  pagination.pageSize = pag.pageSize;
  pagination.current = pag.current;
  user_list();
};

const user_list = async () => {
  try {
    const response = await http.get("/api/users/userlist", {
      params: {
        username: name.value,
        userrole: role.value,
        page_size: pagination.pageSize,
        page: pagination.current,
      },
    });
    
    dataSource.value = response.data.results.users.map((user:any) => ({
      ...user,
      key: user.id,
    }));
    
    pagination.total = response.data.results.total;
    console.log(response)
  } catch (error) {
    console.error("请求失败：", error);
    message.error("获取用户列表失败");
  }
};

// 新增用户相关
const open = ref(false);
const formRef = ref();
const formState = reactive({
  username: "",
  email: "",
  role: null,
  password: "123456",
});

const labelCol = { span: 5 };
const wrapperCol = { span: 13 };

const rules = {
  username: [
    { required: true, message: "请输入用户名字", trigger: "change" },
    { min: 2, max: 10, message: "长度为2到10个字符串", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入用户密码", trigger: "change" },
    { min: 6, max: 20, message: "长度为6到20个字符串", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "change" },
    {
      type: "string",
      pattern: /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  role: [{ required: true, message: "请选择角色名", trigger: "change" }],
};

const showModal = () => {
  open.value = true;
};

const add_user = async () => {
  try {
    const response = await http.post("/api/users/add", {
      username: formState.username,
      email: formState.email,
      role_id: formState.role,
      password: formState.password,
    });
    
    message.success(response.data.msg);
    user_list();
    open.value = false;
    formRef.value.resetFields();
  } catch (error) {
    console.error("请求失败：", error);
    message.error("添加用户失败");
  }
};

const handleOk = () => {
  formRef.value.validate()
    .then(() => add_user())
    .catch((error:any) => console.log("验证失败", error));
};

// 编辑用户相关
const open_edit = ref(false);
const formRef_edit = ref();
const formState_edit = reactive({
  username: "",
  email: "",
  role: null,
});
const edit_id = ref<number>();

const showModal_edit = (record:any) => {
  open_edit.value = true;
  formState_edit.username = record.username;
  formState_edit.email = record.email;
  formState_edit.role = record.role_id;
  edit_id.value = record.id;
};

const edit_save = async () => {
  try {
    const response = await http.post("/api/users/edit_set", {
      id: edit_id.value,
      username: formState_edit.username,
      email: formState_edit.email,
      role: formState_edit.role,
    });
    
    message.success(response.data.msg);
    user_list();
    open_edit.value = false;
  } catch (error) {
    console.error("请求失败：", error);
    message.error("修改用户失败");
  }
};

const handleOk_edit = () => {
  formRef_edit.value.validate()
    .then(() => edit_save())
    .catch((error:any) => console.log("验证失败", error));
};

// 删除用户
const del_user_t = (id: number) => {
  Modal.confirm({
    title: "删除用户",
    // icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要删除此用户吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        const response = await http.get("/api/users/delete_t", {
          params: { id },
        });
        message.success(response.data.msg);
        user_list();
      } catch (error) {
        console.error("请求失败：", error);
        message.error("删除用户失败");
      }
    },
  });
};

onMounted(() => {
  user_list();
  all_permission()
});
</script>

<style scoped>
.role-tag {
  border: none;
  background-color: #f4f4f5;
  border-radius: 5px;
  color: #92969b;
  padding: 2px 8px;
}

:deep(.ant-btn > .anticon + span),
:deep(.ant-btn > span + .anticon) {
  margin-inline-start: 0;
}
</style>